<template>
  <div class="tab" ref="tabDom">
    <h1>是否覆盖</h1>
    <transition :name="position">
      <div class="tab_line" v-if="show">
        <slot><div style="width: 100px;height: 100px;background-color: red">11</div></slot>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'tab-line',
  props: {
    showTime: {
      type: Number,
      default: 0
    },
    toScroll: {
      type: Number,
      default: -1
    },
    position: {
      type: String,
      default: 'top'
    },
    cycle: {
      type: Boolean,
      default: false
    }
  },
  data  () {
    return {
      show: false,
      timer: null
    }
  },
  methods: {
    _getScrollTop () {
      let scrollTop = 0
      if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop
      } else if (document.body) {
        scrollTop = document.body.scrollTop
      }
      return scrollTop
    }
  },
  mounted () {
    window.addEventListener('scroll', (ev) => {
      let scroll = this.toScroll
      if (scroll === -1) {
        scroll = this.$refs.tabDom.offsetTop - (window.innerHeight * 2 / 3)
      }
      if (this._getScrollTop() >= scroll) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.show = true
        }, this.showTime)
      } else if (this.cycle && this._getScrollTop() < scroll) {
        clearTimeout(this.timer)
        this.show = false
      }
    })
  },
  destroy () {
    clearTimeout(this.timer)
  }
}
</script>

<style scoped>
  .tab_line.top-enter {
    transform: translateY(100%);
    opacity: 0;
  }
  .tab_line.top-enter-active {
    transition: all 0.3s;
  }
  .tab_line.bottom-enter {
    transform: translateY(-100%);
    opacity: 0;
  }
  .tab_line.bottom-enter-active {
    transition: all 0.3s;
  }
  .tab_line.right-enter {
    transform: translateX(-100%);
    opacity: 0;
  }
  .tab_line.right-enter-active {
    transition: all 0.3s;
  }
  .tab_line.left-enter {
    transform: translateX(100%);
    opacity: 0;
  }
  .tab_line.left-enter-active {
    transition: all 0.3s;
  }
</style>
